//
//  main.m
//  GTSample
//
//  Created by 大塚 恒平 on 10/06/06.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "gts.h"

int main(int argc, char *argv[]) {
    
	FILE *pfText;
 	GPtrArray *vertices;
 	double dX, dY, dZ;
 	GSList *list = NULL;
 	GtsTriangle *t;
 	guint i;
 	GtsSurface *surface;
 	GtsVertex *v1, *v2, *v3;
	
	// 頂点配列の作成
	vertices = g_ptr_array_new();
	
	g_ptr_array_add( vertices,gts_vertex_new( gts_vertex_class (), 1.0, 1.0, 0.0 ) );
	g_ptr_array_add( vertices,gts_vertex_new( gts_vertex_class (), 2.0, 1.0, 0.0 ) );
	g_ptr_array_add( vertices,gts_vertex_new( gts_vertex_class (), 1.0, 2.0, 0.0 ) );
	g_ptr_array_add( vertices,gts_vertex_new( gts_vertex_class (), 2.0, 2.0, 0.0 ) );

	// 頂点配列をリストにコピー
	for ( i = 0; i < vertices->len; i++ )
	  list = g_slist_prepend( list, g_ptr_array_index( vertices, i ) );

	// 全頂点を確実に包含する三角形を作成
	t = gts_triangle_enclosing( gts_triangle_class(), list, 100. );
	g_slist_free( list );
	gts_triangle_vertices( t, &v1, &v2, &v3 );

	// 包含三角形からGtsSurfaceを作成
	surface = gts_surface_new( gts_surface_class(),
		gts_face_class(),
		gts_edge_class(),
		gts_vertex_class() );

	gts_surface_add_face( surface, gts_face_new( gts_face_class(),
												t->e1, t->e2, t->e3) );
	// 包含三角形にファイルの頂点を１つずつ追加
	// 追加された頂点と包含三角形は常にdelaunay分割になっている
	for ( i = 0; i < vertices->len; i++ )
	{
		GtsVertex * vi = (GtsVertex *)g_ptr_array_index (vertices, i);
		GtsVertex * v = gts_delaunay_add_vertex (surface, vi, NULL);

		g_assert (v != vi);
		if (v != NULL)
		{
			gts_vertex_replace (vi, v);
		}
	}
	
	// 読み込んだ頂点配列を開放
	g_ptr_array_free( vertices, TRUE );

	// 包含三角形の頂点だけを削除
	gts_allow_floating_vertices = TRUE;
	gts_object_destroy (GTS_OBJECT (v1));
	gts_object_destroy (GTS_OBJECT (v2));
	gts_object_destroy (GTS_OBJECT (v3));
	gts_allow_floating_vertices = FALSE;

	NSString* cachePath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString* outPath    = [cachePath stringByAppendingPathComponent:@"test.gts"];
	
	FILE *fp;	/* (1)ファイルポインタの宣言 */
	if ((fp = fopen([outPath cStringUsingEncoding:1], "w")) == NULL) {
		printf("file open error!!\n");
		exit(EXIT_FAILURE);	/* (3)エラーの場合は通常、異常終了する */
	}
	
	gts_surface_write (surface, fp);
	
	fclose(fp);
	
	gts_object_destroy( GTS_OBJECT( surface ) );

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
